/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/linked-list-cycle-ii
   @Language: C++
   @Datetime: 19-11-19 11:26
   */

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode *detectCycle(ListNode *head) {
		ListNode *p, H(-1);
		for(H.next=head, p=&H; p && p->next; head=head->next){
			p=p->next->next;
			if(p==head) break;
		}
		if(!p || !(p->next)) return NULL;
		for(p=&H; (p=p->next) != (head=head->next););
		return p;
	}
};
